package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

//服务器代码
public class UdpEchoServer {
    private DatagramSocket socket;

    //需要指定服务器的端口号
    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动...");
        while(true) {
            //接收客户端的请求数据包
            //接收传输层的数据包的载荷部分
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(requestPacket);//输出型参数

            //解析请求，计算响应
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());
            String response = process(request);

            //将响应的数据包返回给客户端
            //由于 UDP 数据包没有保存对端的IP和端口号，所以要传入
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), response.getBytes().length,
                    requestPacket.getSocketAddress());

            //发送响应数据包
            socket.send(responsePacket);

            //打印日志
            System.out.printf("[%s : %d] request:%s response:%s\n", requestPacket.getAddress(),
                    requestPacket.getPort(), request, response);
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(9090);
        server.start();
    }
}
